<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="auto">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="菜单名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button type="success" icon="plus" @click="handleOpenDialog('0')">新增</el-button>
        </div>
      </div>

      <el-table
        ref="dataTableRef"
        :data="menuTableData"
        :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
        }"
        class="data-table__content"
        @row-click="handleRowClick"
      >
        <el-table-column label="菜单名称" min-width="200">
          <template #default="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.type === MenuTypeEnum.CATALOG" type="warning">目录</el-tag>
            <el-tag v-if="scope.row.type === MenuTypeEnum.MENU" type="success">菜单</el-tag>
            <el-tag v-if="scope.row.type === MenuTypeEnum.BUTTON" type="danger">按钮</el-tag>
            <el-tag v-if="scope.row.type === MenuTypeEnum.EXTLINK" type="info">外链</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="路由名称" align="left" width="150" prop="routeName" />
        <el-table-column label="路由路径" align="left" width="150" prop="routePath" />
        <el-table-column label="组件路径" align="left" width="250" prop="component" />
        <el-table-column label="权限标识" align="center" width="200" prop="perm" />
        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.visible === 1" type="success">显示</el-tag>
            <el-tag v-else type="info">隐藏</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" width="80" prop="sort" />
        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-if="scope.row.type == MenuTypeEnum.CATALOG || scope.row.type == MenuTypeEnum.MENU"
              type="primary"
              link
              size="small"
              icon="plus"
              @click.stop="handleOpenDialog(scope.row.id)"
            >
              新增
            </el-button>

            <el-button
              type="primary"
              link
              size="small"
              icon="edit"
              @click.stop="handleOpenDialog(undefined, scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              icon="delete"
              @click.stop="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      size="600px"
      @close="handleCloseDialog"
    >
      <el-form ref="menuFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="父级菜单" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            placeholder="选择上级菜单"
            :data="menuOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入菜单名称" />
        </el-form-item>

        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="formData.type" @change="handleMenuTypeChange">
            <el-radio :value="MenuTypeEnum.CATALOG">目录</el-radio>
            <el-radio :value="MenuTypeEnum.MENU">菜单</el-radio>
            <el-radio :value="MenuTypeEnum.BUTTON">按钮</el-radio>
            <el-radio :value="MenuTypeEnum.EXTLINK">外链</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="formData.type == MenuTypeEnum.EXTLINK" label="外链地址" prop="path">
          <el-input v-model="formData.routePath" placeholder="请输入外链完整路径" />
        </el-form-item>

        <el-form-item v-if="formData.type == MenuTypeEnum.MENU" prop="routeName">
          <el-input v-model="formData.routeName" placeholder="User" />
        </el-form-item>

        <el-form-item
          v-if="formData.type == MenuTypeEnum.CATALOG || formData.type == MenuTypeEnum.MENU"
          prop="routePath"
        >
          <el-input
            v-if="formData.type == MenuTypeEnum.CATALOG"
            v-model="formData.routePath"
            placeholder="system"
          />
          <el-input v-else v-model="formData.routePath" placeholder="user" />
        </el-form-item>

        <el-form-item v-if="formData.type == MenuTypeEnum.MENU" prop="component">
          <el-input v-model="formData.component" placeholder="system/user/index" style="width: 95%">
            <template v-if="formData.type == MenuTypeEnum.MENU" #prepend>src/views/</template>
            <template v-if="formData.type == MenuTypeEnum.MENU" #append>.vue</template>
          </el-input>
        </el-form-item>

        <el-form-item v-if="formData.type !== MenuTypeEnum.BUTTON" prop="visible" label="显示状态">
          <el-radio-group v-model="formData.visible">
            <el-radio :value="1">显示</el-radio>
            <el-radio :value="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            style="width: 100px"
            controls-position="right"
            :min="0"
          />
        </el-form-item>

        <!-- 权限标识 -->
        <el-form-item v-if="formData.type == MenuTypeEnum.BUTTON" label="权限标识" prop="perm">
          <el-input v-model="formData.perm" placeholder="sys:user:add" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

// 菜单类型枚举
enum MenuTypeEnum {
  CATALOG = "CATALOG",
  MENU = "MENU",
  BUTTON = "BUTTON",
  EXTLINK = "EXTLINK",
}

const queryFormRef = ref();
const menuFormRef = ref();

const dialog = reactive({
  title: "新增菜单",
  visible: false,
});

// 查询参数
const queryParams = reactive({
  keywords: "",
});
// 菜单表格数据
const menuTableData = ref<any[]>([]);
// 顶级菜单下拉选项
const menuOptions = ref<any[]>([]);
// 菜单表单数据
const formData = ref({
  id: undefined,
  parentId: "0",
  name: "",
  type: MenuTypeEnum.MENU,
  routeName: "",
  routePath: "",
  component: "",
  visible: 1,
  sort: 1,
  perm: "",
});
// 表单验证规则
const rules = reactive({
  parentId: [{ required: true, message: "请选择父级菜单", trigger: "blur" }],
  name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择菜单类型", trigger: "blur" }],
  routeName: [{ required: true, message: "请输入路由名称", trigger: "blur" }],
  routePath: [{ required: true, message: "请输入路由路径", trigger: "blur" }],
  component: [{ required: true, message: "请输入组件路径", trigger: "blur" }],
  visible: [{ required: true, message: "请选择显示状态", trigger: "change" }],
});

// 选择表格的行菜单ID
const selectedMenuId = ref<string | undefined>();

// 模拟初始菜单数据
const initialMenuData = [
  {
    id: 1,
    parentId: 0,
    name: "系统管理",
    type: MenuTypeEnum.CATALOG,
    routeName: "",
    routePath: "/system",
    component: "Layout",
    sort: 1,
    visible: 1,
    perm: null,
    children: [
      {
        id: 2,
        parentId: 1,
        name: "用户管理",
        type: MenuTypeEnum.MENU,
        routeName: "User",
        routePath: "user",
        component: "system/user/index",
        sort: 1,
        visible: 1,
        perm: null,
      },
    ],
  },
];

// 查询菜单
function handleQuery() {
  // 这里简单模拟查询，实际可以根据关键词过滤
  menuTableData.value = initialMenuData;
}

// 重置查询
function handleResetQuery() {
  queryParams.keywords = "";
  handleQuery();
}

// 行点击事件
function handleRowClick(row: any) {
  selectedMenuId.value = row.id;
}

/**
 * 打开表单弹窗
 *
 * @param parentId 父菜单ID
 * @param menuId 菜单ID
 */
function handleOpenDialog(parentId?: string, menuId?: string) {
  // 生成菜单选项
  function generateOptions(data: any[]) {
    return data.map((item) => ({
      value: item.id.toString(),
      label: item.name,
      children: item.children ? generateOptions(item.children) : undefined,
    }));
  }
  menuOptions.value = [
    { value: "0", label: "顶级菜单", children: generateOptions(initialMenuData) },
  ];

  dialog.visible = true;
  if (menuId) {
    dialog.title = "编辑菜单";
    const menu = findMenuById(menuId);
    if (menu) {
      formData.value = { ...menu };
    }
  } else {
    dialog.title = "新增菜单";
    formData.value = {
      id: undefined,
      parentId: parentId?.toString(),
      name: "",
      type: MenuTypeEnum.MENU,
      routeName: "",
      routePath: "",
      component: "",
      visible: 1,
      sort: 1,
      perm: "",
    };
  }
}

// 查找菜单
function findMenuById(id: string) {
  function search(data: any[]) {
    for (const item of data) {
      if (item.id.toString() === id) {
        return item;
      }
      if (item.children) {
        const result = search(item.children);
        if (result) {
          return result;
        }
      }
    }
    return null;
  }
  return search(initialMenuData);
}

// 菜单类型切换
function handleMenuTypeChange() {
  // 可根据实际需求处理类型切换逻辑
}

/**
 * 提交表单
 */
function handleSubmit() {
  (menuFormRef.value as any).validate((isValid: boolean) => {
    if (isValid) {
      const menuId = formData.value.id;
      if (menuId) {
        // 修改菜单
        const menu = findMenuById(menuId.toString());
        if (menu) {
          Object.assign(menu, formData.value);
        }
        ElMessage.success("修改成功");
      } else {
        // 新增菜单
        const newId = Date.now();
        const newMenu = { ...formData.value, id: newId };
        const parentMenu = findMenuById(formData.value.parentId);
        if (parentMenu) {
          if (!parentMenu.children) {
            parentMenu.children = [];
          }
          parentMenu.children.push(newMenu);
        } else {
          initialMenuData.push(newMenu);
        }
        ElMessage.success("新增成功");
      }
      handleCloseDialog();
      handleQuery();
    }
  });
}

// 删除菜单
function handleDelete(menuId: string) {
  if (!menuId) {
    ElMessage.warning("请勾选删除项");
    return false;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      function removeMenu(data: any[]) {
        for (let i = 0; i < data.length; i++) {
          const item = data[i];
          if (item.id.toString() === menuId) {
            data.splice(i, 1);
            return true;
          }
          if (item.children) {
            if (removeMenu(item.children)) {
              return true;
            }
          }
        }
        return false;
      }
      removeMenu(initialMenuData);
      ElMessage.success("删除成功");
      handleQuery();
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

function resetForm() {
  (menuFormRef.value as any).resetFields();
  (menuFormRef.value as any).clearValidate();
  formData.value = {
    id: undefined,
    parentId: "0",
    name: "",
    type: MenuTypeEnum.MENU,
    routeName: "",
    routePath: "",
    component: "",
    visible: 1,
    sort: 1,
    perm: "",
  };
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
/* 可以添加一些自定义样式 */
</style>
